package _022_2_12

type ListNode struct {
	Val  int
	Next *ListNode
}

func deleteDuplicates(head *ListNode) *ListNode {
	myHead := &ListNode{
		Next: head,
	}

	if myHead.Next == nil {
		return nil
	}

	for temp := myHead; temp.Next.Next != nil; {
		var begNode *ListNode
		var endNode *ListNode
		if temp.Next.Val == temp.Next.Next.Val {
			begNode = temp
		} else {
			temp = temp.Next
			continue
		}

		for temp.Next.Next != nil {
			if begNode.Next.Val != temp.Next.Next.Val {
				endNode = temp.Next.Next
			}
			temp = temp.Next
		}

		for begNode.Next != endNode {
			begNode.Next = begNode.Next.Next
		}

		temp = begNode
	}

	return myHead.Next

}

func deleteDuplicates2(head *ListNode) *ListNode {
	node := head
	parent := node
	shouldDel := false
	if head == nil {
		return head
	}
	for node.Next != nil {
		if node.Val == node.Next.Val {
			node.Next = node.Next.Next
			shouldDel = true
			continue
		}

		if shouldDel {
			shouldDel = false
			if parent == node {
				parent = node.Next
				head = parent
				node = node.Next
				continue
			}
			parent.Next = node.Next

			node = node.Next
			continue
		}
		parent = node
		node = node.Next
	}

	if shouldDel {
		if head == node {
			head = head.Next
		} else {
			parent = node.Next
		}
	}
	return head
}
